import axios from "axios"
import { message } from "antd"
import router from "@/router"
import { TOKEN } from "@/constants"
import type { AxiosRequestConfig } from "axios"

type Result<T> = {
  code: number
  data: T
  msg: string
}

// axios 实例
const instance = axios.create({
  baseURL: "http://192.168.10.13:8878/api",
  timeout: 10000,
  withCredentials: true
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem(TOKEN) ?? ""
    if (token) {
      // 请求时携带 token
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  (err) => {
    return err
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    const data = res.data

    if (data.code !== 1) {
      throw new Error(data.msg)
    }

    return data
  },
  (err) => {
    if (!err.response) {
      message.error("网络异常")
    }

    // 处理 http 错误状态码
    switch (err.response.status) {
      case 401:
        message.error({
          content: "登录已过期，请重新登录",
          key: "401"
        })
        router.navigate("/login", { replace: true })
        break
      case 500:
        message.error({
          content: "服务器异常，请联系管理员",
          key: "500"
        })
        break
      case 502:
        message.error({
          content: "服务器异常，请联系管理员",
          key: "502"
        })
        break
      default:
        break
    }

    return err
  }
)

// 请求封装
function request<T>(config: AxiosRequestConfig) {
  return new Promise<Result<T>>((resolve, reject) => {
    instance
      .request<any, Result<T>>(config)
      .then((res) => resolve(res))
      .catch((err) => reject(err))
  })
}

function get<T = any>(config: AxiosRequestConfig) {
  return request<T>({ ...config, method: "GET" })
}

function post<T = any>(config: AxiosRequestConfig) {
  return request<T>({ ...config, method: "POST" })
}

export { get, post }
